def get_breadcrumb(cat3):
    """面包屑导航数据获取"""
    # 查询二级分类和一级分类
    cat2 = cat3.parent
    cat1 = cat2.parent

    # 组织面包屑导航数据
    breadcrumb = {
        'cat1': cat1.name,
        'cat2': cat2.name,
        'cat3': cat3.name
    }

    return breadcrumb

import copy
from collections import OrderedDict

from goods.models import GoodsChannel
from goods.models import SKU
from goods.models import SKUImage
from goods.models import SKUSpecification
from goods.models import SPUSpecification
from goods.models import SpecificationOption


def get_categories():
    """商品分类数据获取"""
    categories = OrderedDict()
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')

    for channel in channels:
        group_id = channel.group_id

        if group_id not in categories:
            categories[group_id] = {
                'channels': [],
                'sub_cats': []
            }

        # 获取频道对应的一级分类
        cat1 = channel.category

        categories[group_id]['channels'].append({
            'id': cat1.id,
            'name': cat1.name,
            'url': channel.url
        })

        # 获取一级分类的下级分类(二级分类)
        cat2s = cat1.subs.all()

        for cat2 in cat2s:
            cat2.sub_cats = []

            # 获取二级分类的下级分类(三级分类)
            cat3s = cat2.subs.all()
            for cat3 in cat3s:
                cat2.sub_cats.append(cat3)

            categories[group_id]['sub_cats'].append(cat2)

    return categories


def get_goods_and_spec(sku_id):
    """获取指定sku商品的信息"""
    sku = SKU.objects.get(id=sku_id)

    # 获取sku图片数据
    sku.images = SKUImage.objects.filter(sku=sku)

    # 获取sku所属spu
    spu = sku.spu

    # 获取sku的规格选项数据
    keys = []
    sku_specs = SKUSpecification.objects.filter(sku=sku).order_by('spec_id')

    for sku_spec in sku_specs:
        keys.append(sku_spec.option.id)

    # 获取该spu下的所有sku商品
    skus = SKU.objects.filter(spu=spu)

    # 获取该spu下的所有sku商品的规格选项和sku商品的对应关系
    skus_dict = {}
    for temp_sku in skus:
        sku_specs = SKUSpecification.objects.filter(sku=temp_sku).order_by('spec_id')

        temp_keys = []
        for sku_spec in sku_specs:
            temp_keys.append(sku_spec.option.id)

        skus_dict[tuple(temp_keys)] = temp_sku.id

    # 在其他规格选项不变的情况下，在每个选项上绑定对应的sku
    # 获取spu下的规格数据
    specs = SPUSpecification.objects.filter(spu=spu).order_by('id')

    for index, spec in enumerate(specs):
        temp_keys = copy.deepcopy(keys)
        # 获取规格下的选项数据
        options = SpecificationOption.objects.filter(spec=spec)

        for option in options:
            temp_keys[index] = option.id
            option.sku_id = skus_dict.get(tuple(temp_keys))

        spec.spec_options = options

    return spu, specs, sku